<!--车辆管理页-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">订单管理</span>
    <el-button @click="beforeAddOrder"
               type="primary" style="float:right;margin-top:13px;">
      新建订单</el-button>
  </div>
  <!-- 新增订单弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width:1000px;padding:40px;"
             :before-close="handleClose">
    <el-form label-width="180px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="课程列表">
            <el-table :data="courseArr">
              <el-table-column label="编号" prop="courseId" align="center" width="80px"></el-table-column>
              <el-table-column prop="courseName" label="课程名称" align="center"></el-table-column>
              <el-table-column prop="description" label="课程描述" align="center"></el-table-column>
              <el-table-column prop="cover" label="课程封面" align="center"></el-table-column>
              <el-table-column prop="price" label="课程价格" align="center"></el-table-column>
              <el-table-column label="选择" align="center">
                <template #default="scope">
                  <el-button link type="primary" @click="bindNewCourse(scope.row.id)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="购买时间">
            <el-date-picker type="date"  v-model="s"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            @change="validateDate"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="删除时间">
            <el-date-picker type="date" v-model="saveOrderForm.createTime"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            @change="validateDate"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="购买价格">
            <el-input placeholder="请输入内容" v-model="saveOrderForm.price"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveOrder">确定</el-button>
    </template>
  </el-dialog>
  <!-- 课程搜索搜索卡片 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="订单编号">
        <el-input placeholder="请输入内容" style="width:220px;" v-model="searchOrderForm.orderid"></el-input>
      </el-form-item>
      <el-form-item label="课程名称" style="width:290px;">
        <el-input placeholder="请输入内容" style="width:220px;" v-model="searchOrderForm.courseName"></el-input>
      </el-form-item>
      <el-form-item label="订单状态" style="width:290px;">
        <el-input placeholder="请输入内容" style="width:220px;" v-model="searchOrderForm.status"></el-input>
      </el-form-item>
      <el-form-item label="订单创建时间" style="width:290px;">
        <el-date-picker
            v-model="searchOrderForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:220px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadOrder">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 订单列表 -->
  <el-card style="margin:20px;">
    <el-table :data="OrderArr">
      <el-table-column prop="orderId" label="编号" width="80" align="center"/>

      <el-table-column prop="price" label="购买价格" align="center"/>
      <el-table-column prop="createTime" label="购买时间" align="center"/>
      <el-table-column prop="updateTime" label="取消时间" align="center"/>
      <el-table-column prop="status" label="订单状态" align="center"
                       :formatter="OrderTypeFormatter"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small"
                     @click="editOrder(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small"
                     @click="PayOrder(scope.row.orderId)">支付</el-button>
          <div>
            <!-- 其他内容 -->
            <el-button @click="generateQrCode">生成二维码</el-button>
            <div v-if="qrCode">
              <img :src="qrCode" alt="QR Code" style="width: 200px; height: 200px;">
            </div>
          </div>
          <el-button link type="primary" size="small"
                     @click="OrderVehicle(scope.row.orderId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import QRCode from "qrcode";

// 定义保存二维码图片的变量
const qrCode = ref(null);

// 定义生成二维码的方法
const generateQrCode = async () => {
  try {
    const response = await axios.post(BASE_URL + '/api/order/createQrCode', {
      orderId: '123456789', // 替换为实际的订单ID
      price: '100.00' // 替换为实际的订单金额
    });
    if (response.data.qrCode) {
      qrCode.value = await QRCode.toDataURL(response.data.qrCode);
    } else {
      alert('二维码生成失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error(error);
    alert('生成二维码时发生错误');
  }
};
//定义数组用来保存可以添加订单的可选订单列表
const courseArr = ref([]);


//控制新增车辆弹窗是否显示
const dialogVisible = ref(false);
//定义变量控制dialog的标题
const dialogTitle = ref('新增订单');



//定义对象用来保存车辆的搜索条件
const searchOrderForm = ref({orderId:'',courseName:'',status:'',createTime:''});
//定义数组用来保存车辆表格数据
const OrderArr = ref([]);

//定义加载订单的方法
const loadOrder = ()=>{
  let data = qs.stringify(searchOrderForm.value);
  axios.get(BASE_URL+'/api/order/list?'+data).then((response)=>{
    if (response.data.code == 2000) {
      OrderArr.value = response.data.data;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
onMounted(()=>{
  loadOrder();
})
//定义重置搜索的方法
const resetSearch = ()=>{
  searchOrderForm.value = {};
  loadOrder();
}
//定义处理订单类型表格列的显示文字转换 10=>轿车
const OrderTypeFormatter = (row,column,cellValue,index)=>{
   if(cellValue == 0){
     cellValue = '未支付';
   }else if(cellValue == 1){
     cellValue = '已支付';
   }else if(cellValue == 2){
     cellValue = '已取消';
   }
  return cellValue;
}


//定义保存订单表单数据的对象
const saveOrderForm = ref({
orderid:'',
  userid:'',
  courseid:'',
  price:'',
  status:'',
  createTime:'',
  updateTime:''
});
//
const saveCourseForm = ref({
  courseId:'',
 courseName:'',
  description:'',
  cover:'',
  price:''

});
//在点击"新增订单"按钮时调用
const beforeAddOrder = ()=>{
  dialogTitle.value = '新增订单';
  dialogVisible.value = true;
  let data = qs.stringify(saveCourseForm.value);
  axios.get(BASE_URL+'/v1/course/select?'+data).then((response)=>{
    if (response.data.code == 2000) {
      courseArr.value = response.data.data;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
//校验购买时间与上牌时间的合理性
const validateDate = ()=>{
  const buyTime = saveOrderForm.value.createTime;
  const regTime = saveOrderForm.value.updateTime;
  if(regTime && buyTime && new Date(regTime) <= new Date(buyTime)){
    ElMessage.error('上牌时间不能早于购买时间!');
    saveOrderForm.value.createTime = '';
  }
}
//定义保存订单的方法
const saveOrder = ()=>{

  if(!saveOrderForm.value.courseid || saveOrderForm.value.code.trim()==''){
    ElMessage.error('请输入课程!');
    return;
  }
  if(!saveOrderForm.value.createTime){
    ElMessage.error('请选择购买时间!');
    return;
  }
  console.log(saveOrderForm.value);
  let data = qs.stringify(saveOrderForm.value);
  axios.post(BASE_URL+'/api/order/create',data).then((response)=>{
    if(response.data.code == 2000){
      ElMessage.success('保存成功!');
      dialogVisible.value = false;//关闭弹窗
      saveOrderForm.value = {};//清空表单
      loadOrder();//新增成功后,需要重新加载数据!
    }else{
      ElMessage.error('订单号不允许重复!');
    }
  })
}
//定义保存车辆表单弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您是否要关闭本弹窗?')){
    saveOrderForm.value = {};
    dialogVisible.value = false;
  }
}
//定义编辑订单的方法
const editOrder = (id)=>{
  dialogTitle.value = '编辑订单';
  dialogVisible.value = true;
  //根据当前车辆id,查询并回显当前车辆的详细数据
  axios.get(BASE_URL+'/api/order/pay?id='+id).then((response)=>{
    if (response.data.code == 2000) {
      saveOrderForm.value = response.data.data[0];
      console.log("我是回显的数据:");
      console.log(saveOrderForm.value);
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

// 定义支付订单的方法
const PayOrder = (id) => {
  axios.get(BASE_URL + '/alipay/pay', { params: { orderId: id } }).then((response) => {
    if (response.data.includes('<form')) {
      const form = document.createElement('form');
      form.innerHTML = response.data;
      document.body.appendChild(form);
      form.submit();
    } else {
      alert('支付请求失败，请稍后再试');
    }
  }).catch((error) => {
    console.error(error);
    alert('支付请求失败，请稍后再试');
  });

  axios.post(BASE_URL+'/api/order/detail/'+id).then((response)=>{
    if(response.data.code == 2000){
      ElMessage.success('支付成功!');
      loadOrder();
    }else{
      ElMessage.error(response.data.msg);
    }
  })
};
//定义删除订单的方法
const OrderVehicle = (id)=>{
  if(confirm('您确认要删除该车辆吗?')){
    axios.post(BASE_URL+'/api/order/delete/'+id).then((response)=>{
      if(response.data.code == 2000){
        ElMessage.success('删除成功!');
        loadOrder();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}
</script>